import { defineStore } from 'pinia'
import { getPermmenu } from '@/api/menu'
import { listToTree } from '@/utils'
import asyncRoutes from '@/router/asyncRoutes'

export const useMenuStore = defineStore('menu', {
  state() {
    return {
      // 权限数据
      perms: [] as string[],
      // 菜单数据（路由数据）
      menus: [] as IMenu[]
    }
  },

  getters: {
    // 用于左侧菜单的菜单数据
    displayMenus(state) {
      // 1. 先将 menus 中 type === 2 的移除掉。
      const menus = state.menus.filter((item) => item.type !== 2)
      // 2. 根据 parentId 将 menus 数据转成 tree 数据格式
      return listToTree(menus, null)
    }
  },

  actions: {
    /**
     * 获取权限与菜单
     */
    async getPermmenu() {
      const { data } = await getPermmenu()
      // 将接口数据写入state
      this.perms = data.perms
      this.menus = data.menus
    },

    /**
     * 构造生成路由对象数组
     *  [{ path: 'xxxx', component: xxxx }]
     */
    async genAccessRoutes() {
      const { data } = await getPermmenu()
      // 将接口数据写入state
      this.perms = data.perms
      this.menus = data.menus

      const accessRoutes = data.menus
        .filter((item) => item.type === 1)
        .map((item) => {
          return {
            path: item.router as string,
            // component: () => import('@/views/test.vue')
            // PS import() 如果使用变量的话，就无法使用路径别名
            // component: () => import(`../views/${item.viewPath}`)
            component: asyncRoutes['../views/' + item.viewPath!]
          }
        })

      return accessRoutes
    }
  }
})